package cn.ywang.client;

import cn.ywang.model.RpcRequest;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @Auther: BeatificWang
 * @Date: 2018/11/25 23:33
 */
public class TCPTransport {
	private String serviceAddress;

	public TCPTransport(String serviceAddress) {
		this.serviceAddress = serviceAddress;
	}

	private Socket newSocket() {
		Socket socket = null;
		try {
			String[] address = this.serviceAddress.split(":");
			String host = address[0];
			int port = Integer.parseInt(address[1]);
			socket = new Socket(host, port);
			System.out.println("创建一个新的连接");
		} catch (IOException e) {
			throw new RuntimeException("创建连接失败");
		}
		return socket;
	}

	public Object send(RpcRequest rpcRequest) {
		Socket socket = null;
		Object object = null;
		ObjectOutputStream objectOutputStream = null;
		ObjectInputStream objectInputStream = null;
		try {
			socket = this.newSocket();
			objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
			objectOutputStream.writeObject(rpcRequest);
			objectOutputStream.flush();
			objectInputStream = new ObjectInputStream(socket.getInputStream());
			object = objectInputStream.readObject();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (socket != null) {
				try {
					socket.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (objectOutputStream != null) {
				try {
					objectOutputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (objectInputStream != null) {
				try {
					objectInputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return object;
	}
}
